<!-- 材料信息 -->
<template>
  <div>
    <div class="title pl0">
      <h3>材料信息</h3>
      <el-button
        type="text"
        v-if="isDisable && isLocked == '待锁定'"
        @click="handleEdit"
        >编辑</el-button
      >
    </div>
    <el-table :data="formData.productMaterialList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="50" />
      <!-- <el-table-column
        prop="stockGoodsCode"
        width="150"
        align="center"
        label="规格编号"
      >
      <template slot-scope="scope">
        {{ !scope.row.specification?'选择后显示': scope.row.specification}}
      </template>
      </el-table-column>
      <el-table-column
        prop="school"
        width="150"
        align="center"
        label="物料名称"
      >
        <template slot-scope="scope">
          <el-select
                        filterable
            v-model="scope.row.stockGoodsCode"
            v-if="!isDisable"
            filterable
            placeholder="请选择物料"
            size="small"
            @change="handleMaterialNameChange(scope.row, scope.$index, $event)"
          >
            <el-option
              :label="item.goodsName"
              :value="item.goodsCode"
              v-for="(item, index) in materialList"
              :key="index"
            />
          </el-select>
          <span v-else>{{ scope.row.materialName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="specification"
        width="150"
        align="center"
        label="规格型号"
      >
        <template slot-scope="scope">
          <el-select
                        filterable
            v-model="scope.row.specification"
            v-if="!isDisable"
            placeholder="请选择规格型号"
            size="small"
          >
            <el-option
              :label="item.specificationName"
              :value="item.specificationCode"
              v-for="(item, index) in scope.row.list"
              :key="index"
            />
          </el-select>
          <span v-else>{{ formatData(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="materialType"
        width="150"
        align="center"
        label="物料类型"
      >
      <template slot-scope="scope">
        {{ !scope.row.stockGoodsCode?'选择后显示': scope.row.materialType}}
      </template>
      </el-table-column> -->

      <el-table-column
        prop="specificationCode"
        width="150"
        align="center"
        label="规格编号"
      >
        <template slot-scope="scope">
          {{ scope.row.specification || "--" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="materialType"
        width="100"
        align="center"
        label="物料类型"
      >
        <template slot-scope="scope">
          {{ scope.row.materialType || "--" }}
        </template>
      </el-table-column>
      <el-table-column prop="school" width="250" align="center" label="供应商">
        <template slot-scope="scope">
          <el-select
                        filterable
            v-model="scope.row.supplierCode"
            placeholder="请选择供应商"
            v-if="!isDisable"
            size="small"
            @change="supplierChange(scope.row, $event)"
          >
            <el-option
              :key="item.supplierID"
              :label="item.supplierName"
              :value="item.supplierCode"
              v-for="(item, index) in allSupliers"
            />
          </el-select>
          <span v-else-if="allSupliers.length>0">{{ formatData(allSupliers,scope.row.supplierCode,'supplierName','supplierCode') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="school"
        width="200"
        align="center"
        label="物料名称"
      >
        <template slot-scope="scope">
          <el-select
                        filterable
            v-model="scope.row.stockGoodsCode"
            placeholder="请选择物料"
            v-if="!isDisable"
            size="small"
            @change="handleMaterialNameChange(scope.row, scope.$index, $event)"
          >
            <el-option
              :label="item.goodsName"
              :value="item.goodsCode"
              v-for="(item, index) in scope.row.materialList"
              :key="index"
            />
          </el-select>
          <span v-else-if="scope.row.materialList.length>0">{{ formatData(scope.row.materialList,scope.row.stockGoodsCode,'goodsName','goodsCode') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="specificationCode"
        width="150"
        align="center"
        label="规格型号"
      >
        <template slot-scope="scope">
          <el-select
                        filterable
          v-if="!isDisable"
            v-model="scope.row.specification"
            @change="handleSpecificationChange(scope.row, scope.$index)"
            placeholder="请选择规格型号"
            size="small"
          >
            <el-option
              :label="item.specificationName"
              :value="item.specificationCode"
              v-for="(item, index) in scope.row.goodsSpecificationList"
              :key="index"
            />
          </el-select>
          <span v-else-if="scope.row.goodsSpecificationList.length>0">{{ formatData(scope.row.goodsSpecificationList,scope.row.specification,'specificationName','specificationCode') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="prop1"
        width="150"
        align="center"
        label="使用类型"
      >
        <template slot-scope="scope">
          <el-select
            filterable
            v-if="!isDisable"
            v-model="scope.row.useType"
            placeholder="请选择使用类型"
            size="small"
          >
            <el-option
              label="常用料"
              :value="0"
            />
            <el-option
              label="备用料"
              :value="1"
            />
          </el-select>
          <span v-else>{{ scope.row.useType==0?"常用料":"备用料" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="materialRemark" align="center" label="物料备注">
        <template slot-scope="scope">
          <el-input
            v-if="!isDisable"
            v-model="scope.row.materialRemark"
            placeholder="请输入内容"
            size="small"
          />
          <span v-else>{{ scope.row.materialRemark }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="100px"
        fixed="right"
        align="center"
        v-if="!isDisable"
      >
        <template slot-scope="scope">
          <el-button
            v-if="formData.productMaterialList.length - 1 != scope.$index"
            type="text"
            @click="handleCopyRow(scope.row, scope.$index)"
            >复制</el-button
          >
          <el-button
            type="text"
            v-if="formData.productMaterialList.length - 1 != scope.$index"
            @click="handleDeleteRow(scope.row, scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="footer mt16" v-if="!isDisable">
      <el-button size="small" @click="handleCancel">取消</el-button>
      <el-button
        size="small"
        class="ml16"
        type="primary"
        @click="handleSave"
        >
        <p>保存</p>
      </el-button>
    </div>
  </div>
</template>

      <script>
import { arraySort, filterSpecifications } from "@/utils";
export default {
  props: {
    productCode: {
      type: String,
      default: () => {
        return "";
      },
    },
    isLocked: {
      type: String,
      default: () => {
        return "";
      },
    },
    isShowEdits:{
      type: Boolean,
      default: () => {
        return false;
      },
    },
    formModel: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    formModel: {
      handler(newVal, oldVal) {
        this.formData.productMaterialList = newVal.productMaterialList;
        // this.formData.productMaterialList.forEach((x) => {
        //   // this.materialList.forEach((item) => {
        //   //   if (x.stockGoodsCode == item.goodsCode) {
        //   //     this.$set(x,'list',item.list)
        //   //     // x.list = item.list;
        //   //   }
        //   // });
        // });
        if (
          this.formData.productMaterialList &&
          this.formData.productMaterialList.length > 0
        ) {
          this.getSelectData();
        }

        this.$forceUpdate();
      },
    },
  },
  data() {
    return {
      formData: {
        productCode: this.productCode,
        productMaterialList: [],
      },
      materialList: [], //物料列表
      allSupliers: [],
      stockGoodsList: [],
      isDisable: true,
    };
  },
  created() {
    // this.getmaterialList();

    //获取供应商
    this.getSupplier();
  },
  methods: {
    getSelectData() {
      this.formData.productMaterialList.forEach((item, index) => {
        this.$api.mater
          .GetGoodsSpecificationBySupplierCode({
            queryBy: 0,
            queryValue: item.supplierCode,
          })
          .then((data) => {
            this.$set(item, "materialList", data);
            item.materialList.forEach((k) => {
              if (item.stockGoodsCode == k.goodsCode) {
                this.$set(
                  item,
                  "goodsSpecificationList",
                  filterSpecifications(
                    k.goodsSpecificationList,
                    item.specification
                  )
                );
                if(item.goodsSpecificationList.length>0){
                  item.goodsSpecificationList.forEach((j)=>{
                    if(item.specification == j.specificationCode){
                      item.specificationCode = j.specificationCode;
                    }
                  })
                }
                item.materialType = k.goodsType;
              }
            });
          });
      });

      console.log(this.formData.productMaterialList);
    },

    //获取物料下拉
    getmaterialList() {
      const parmas = {
        pageIndex: 1,
        pageSize: 9999,
        queryDataBaseFiled: "",
        likeWords: "",
        isShowDisabled: 0,
        groupCode: "",
        categoryCode: "",
        goodsCode: "",
        unitCode: "",
        isDisable: 0,
        isDelete: 0,
      };
      this.$api.business
        .GetMatchPageGoods(parmas)
        .then((res) => {
          this.materialList = res.list;
          this.formData.productMaterialList.forEach((x) => {
            this.materialList.forEach((item) => {
              if (x.stockGoodsCode == item.goodsCode) {
                x.list = item.list;
              }
            });
          });
        })
        .catch(() => {});
    },

    //供应商选择事件
    supplierChange(row, val) {
      row.stockGoodsCode = "";
      row.specification = "";
      row.materialList = [];
      row.goodsSpecificationList = [];
      row.goodsType = "";
      this.$api.mater
        .GetGoodsSpecificationBySupplierCode({
          queryBy: 0,
          queryValue: val,
        })
        .then((res) => {
          this.$set(row, "materialList", res);
          this.$forceUpdate();
        });
    },

    //物料下拉选择事件
    handleMaterialNameChange(row, index, e) {
      if (index == this.formData.productMaterialList.length - 1) {
        this.formData.productMaterialList.push({
          productMaterialID: 0,
          productMaterialCode: "",
          productCode: this.productCode,
          stockGoodsCode: "",
          materialName: "",
          specification: "",
          materialType: "",
          materialRemark: "",
          materialList : [],
          goodsSpecificationList: []
        });
      }
      this.materialList[index].stockGoodsCode = e;
      row.specificationCode = "";
      row.materialList.forEach((item, i) => {
        if (item.goodsCode == e) {
          row.categoryName = item.goodsType;
          row.materialName = item.goodsName;
          this.$set(row, "goodsSpecificationList", item.goodsSpecificationList);
          row.goodsUnitName = item.goodsUnit;
          // row.goodsType = item.goodsType;
          // row.priceUnit = item.priceUnit;
        }
      });
    },

    //规格型号选择事件
    handleSpecificationChange(row, index) {
      // this.ProductForm.mxDataList.forEach((item) => {
      //   if (
      //     item.goodsSpecificationList &&
      //     item.goodsSpecificationList.length > 0
      //   ) {
      //     item.goodsSpecificationList.forEach((x) => {
      //       if (item.specificationCode == x.specificationCode) {
      //         item.productionBatchList = x.productionBatchList;
      //         item.stockQuantity = x.stockQuantity;
      //         item.goodsPrice = x.goodsPrice;
      //         item.stockGoodsCode = x.specificationCode;
      //       }
      //     });
      //   }
      // });
      this.$forceUpdate();
    },

    // 获取供应商
    getSupplier() {
      this.$api.mater.GetAllSuppliers().then((res) => {
        this.allSupliers = res;
      });
    },

    //取消
    handleCancel() {
      this.$confirm("信息尚未保存，是否保存?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      })
        .then(() => {
          this.handleSave();
        })
        .catch(() => {
          this.isShowEdits = true
          this.$emit('showEditEvent',this.isShowEdits)
          this.getDetail(this.productCode);
          this.isDisable = true;
        });
    },

    //删除
    handleDeleteRow(row, index) {
      this.formData.productMaterialList.splice(index, 1);
      // this.formData.productMaterialList.forEach((data,idx)=>{
      //   this.materialList[idx].stockGoodsCode = data.stockGoodsCode;
      //   this.materialList.forEach((item, i) => {
      //     if (item.goodsCode == data.stockGoodsCode) {
      //       debugger
      //       data.materialType = item.categoryName;
      //       data.materialName = item.goodsName;
      //     }
      //   });
      // })
      // console.log(this.formData);
    },

    //复制
    handleCopyRow(row, index) {
      this.formData.productMaterialList.splice(
        index,
        0,
        JSON.parse(JSON.stringify(row))
      );
    },

    //物料下拉选择事件
    handleMaterialNameChange(row, index, e) {
      if (index == this.formData.productMaterialList.length - 1) {
        this.formData.productMaterialList.push({
          productMaterialID: 0,
          productMaterialCode: "",
          productCode: this.productCode,
          stockGoodsCode: "",
          materialName: "",
          specification: "",
          materialType: "",
          materialRemark: "",
          materialList : [],
        goodsSpecificationList: []
        });
      }
      row.materialList.forEach((item, i) => {
        if (item.goodsCode == e) {
          row.materialType = item.goodsType;
          this.$set(row,'goodsSpecificationList',item.goodsSpecificationList)
          // row.goodsType = item.goodsType;
          // row.priceUnit = item.priceUnit;
        }
      });
      row.specification = "";
      // row.productMaterialCode = e.goodsCode;
      // row.materialType = e.categoryName;
      // row.materialName = e.goodsName;
      // this.getStockGoodsList(e);
    },

    // formatData(row) {
    //   let name = "";
    //   this.materialList.forEach((item) => {
    //     if (row.stockGoodsCode == item.goodsCode) {
    //       console.log(item.list);
    //       name = item.list.filter(
    //         (t) => t.specificationCode == row.specification
    //       )[0].specificationName;
    //     }
    //   });
    //   return name;
    // },

    formatData(list,code,lable,value){
      let str = ''
      list.forEach((item)=>{
        if(item[value] == code){
          str = item[lable]
        }
      })
      return str
    },

    // //获取库存物料下拉列表数据
    // getStockGoodsList(e) {
    //   const query = {
    //     groupCode: "", //分组代码，空值查询全部
    //     categoryCode: "", //	分类代码，空值查询全部
    //     supplierCode: "", //供应商代码，空值查询全部
    //     goodsCode: e, //基础物料代码，空值查询全部
    //     likeWords: "", //查询关键字，空值查询全部
    //   };
    //   this.$api.report.GetStockGoodsDataList(query).then((res) => {
    //     this.stockGoodsList = res;
    //   });
    // },

    //保存
    handleSave() {
      this.formData.productMaterialList.forEach((item, index) => {
        if (typeof item.stockGoodsCode == "object") {
          item.stockGoodsCode = item.stockGoodsCode.goodsCode;
        }
        if (!item.stockGoodsCode) {
          this.formData.productMaterialList.splice(index, 1);
        }
      });
      this.$api.business.UpdateProductMaterial(this.formData).then((res) => {
        let obj = {
          state: 4,
          productCode: this.productCode,
        };
        this.$api.business.UpdateProductState(obj).then((res) => {
          this.isShowEdits = true
        this.$emit('showEditEvent',this.isShowEdits)
          this.$message.success("保存成功");
          this.getDetail(this.productCode);
        });
        this.isDisable = true;
      });
    },

    //获取详情
    getDetail(id) {
      this.$emit("init", "");
      // const parmas = {
      //   queryBy: 2,
      //   queryValue: id,
      // };
      // this.$api.business.GetSingleProductByProductCode(parmas).then((res) => {
      //   this.formData.productMaterialList = res.productMaterialList;
      //   this.formData.productMaterialList.forEach((x) => {
      //     this.materialList.forEach((item) => {
      //       if (x.stockGoodsCode == item.goodsCode) {
      //         x.list = item.list;
      //       }
      //     });
      //   });
      //   console.log(this.formData.productMaterialList);
      // });
    },

    //编辑
    handleEdit() {
      if(this.isShowEdits){
        this.isDisable = false
        this.isShowEdits = false
        this.$emit('showEditEvent',this.isShowEdits)
        this.formData.productMaterialList.push({
        productMaterialID: 0,
        productMaterialCode: "",
        productCode: this.productCode,
        stockGoodsCode: "",
        materialName: "",
        specification: "",
        materialType: "",
        materialRemark: "",
        materialList : [],
        goodsSpecificationList: []
      });
      }else{
        this.$message.warning('有未保存的编辑，请保存后再编辑')
      }
    },
  },
};
</script>

      <style lang="scss" scoped>
.footer {
  display: flex;
  justify-content: center;
}

.title h3:before {
  content: "" !important;
  padding-right: 9px !important;
  border-left: 3px solid #3f61f1;
}
</style>
